import React, { useState, useEffect } from "react";
import { Service } from "../api/services/Service";
import type { VidVideo_ } from "../api/models/VidVideo_";
import "./VideoDetail.css";
import {
  canWatchVideo,
  checkAndRefreshVipStatus,
  getToken,
} from "../utils/auth";
import { message, Modal, Input } from "antd";
import { useUser } from "../stores/userStore";

const { TextArea } = Input;

interface VideoDetailProps {
  video: VidVideo_;
  onBack: () => void;
  onLoginRequired: () => void;
  onVideoClick?: (video: VidVideo_) => void;
}

const VideoDetail: React.FC<VideoDetailProps> = ({
  video,
  onBack,
  onLoginRequired,
  onVideoClick,
}) => {
  const { userInfo, refreshUserInfo } = useUser();
  const [relatedVideos, setRelatedVideos] = useState<VidVideo_[]>([]);
  const [loading, setLoading] = useState(false);
  const [isPlaying, setIsPlaying] = useState(false);
  const [isReportModalVisible, setIsReportModalVisible] = useState(false);
  const [reportContent, setReportContent] = useState("");

  useEffect(() => {
    // 页面刷新时获取最新用户信息
    if (userInfo?.id) {
      refreshUserInfo();
    }

    loadRelatedVideos();
  }, [video.id]);

  const loadRelatedVideos = async () => {
    setLoading(true);
    try {
      const response = await Service.relatedVideoListUsingPost({
        current: 1,
        size: 10,
        videoId: video.id,
        compilationId: video.compilationId,
      });
      if (response.data?.records) {
        setRelatedVideos(response.data.records);
      }
    } catch (error) {
      console.error("加载相关视频失败:", error);
    } finally {
      setLoading(false);
    }
  };

  const handlePlayVideo = async () => {
    // 获取最新的用户信息
    const latestUserInfo = await refreshUserInfo();

    // 检查是否可以观看视频
    if (!canWatchVideo(video, latestUserInfo)) {
      // 如果用户已登录但权限不足，尝试刷新用户状态
      if (latestUserInfo) {
        try {
          message.loading("正在检查您的会员状态...", 0);
          const hasVipAccess = await checkAndRefreshVipStatus();
          message.destroy();

          if (hasVipAccess) {
            // 刷新后有权限，重新获取用户信息
            const refreshedUserInfo = await refreshUserInfo();
            message.success("检测到您已是VIP会员，正在为您播放视频");
            // 使用刷新后的用户信息再次检查权限
            if (canWatchVideo(video, refreshedUserInfo)) {
              setIsPlaying(true);
            } else {
              setTimeout(() => {
                window.location.reload();
              }, 1000);
            }
            return;
          } else {
            message.error("该视频需要VIP会员才能观看");
            return;
          }
        } catch (error) {
          message.destroy();
          message.error("检查会员状态失败，该视频需要VIP会员才能观看");
          return;
        }
      } else {
        // 用户未登录，跳转到登录页面
        onLoginRequired();
        return;
      }
    }
    setIsPlaying(true);
  };

  const handleRelatedVideoClick = async (relatedVideo: VidVideo_) => {
    // 获取最新的用户信息
    const latestUserInfo = await refreshUserInfo();
    // 检查是否可以观看视频
    if (!canWatchVideo(relatedVideo, latestUserInfo)) {
      // 如果用户已登录但权限不足，尝试刷新用户状态
      if (latestUserInfo) {
        try {
          message.loading("正在检查您的会员状态...", 0);
          const hasVipAccess = await checkAndRefreshVipStatus();
          message.destroy();

          if (hasVipAccess) {
            // 刷新后有权限，重新获取用户信息
            const refreshedUserInfo = await refreshUserInfo();
            message.success("检测到您已是VIP会员，正在为您播放视频");
            // 使用刷新后的用户信息再次检查权限
            if (canWatchVideo(relatedVideo, refreshedUserInfo)) {
              if (onVideoClick) {
                onVideoClick(relatedVideo);
              } else {
                window.location.href = `/h5/video/${relatedVideo.id}`;
              }
            } else {
              setTimeout(() => {
                window.location.reload();
              }, 1000);
            }
            return;
          } else {
            message.error("该视频需要VIP会员才能观看");
            return;
          }
        } catch (error) {
          message.destroy();
          message.error("检查会员状态失败，该视频需要VIP会员才能观看");
          return;
        }
      } else {
        // 用户未登录，提示需要VIP
        message.error("您需要成为VIP才能观看VIP视频");
        return;
      }
    }

    // 如果有onVideoClick回调，使用它来处理视频点击
    if (onVideoClick) {
      onVideoClick(relatedVideo);
      // 添加短暂延迟后刷新页面，确保视频内容更新
      setTimeout(() => {
        window.location.reload();
      }, 100);
    } else {
      // 兜底方案：直接跳转并刷新页面
      window.location.href = `/h5/video/${relatedVideo.id}`;
    }
  };

  const handleReportSubmit = () => {
    if (!reportContent.trim()) {
      message.error("请输入举报内容");
      return;
    }

    // 这里可以调用API提交举报内容
    // 暂时使用message提示
    if (userInfo?.id) {
      Service.reportSaveUsingPost({
        context: reportContent,
        id: video.id,
      })
        .then(() => {
          message.success("举报已提交，感谢您的反馈！");
          setIsReportModalVisible(false);
          setReportContent("");
        })
        .finally(() => {
          setReportContent("");
        });
    }
  };

  const handleReportCancel = () => {
    setIsReportModalVisible(false);
    setReportContent("");
  };

  return (
    <div className="video-detail-container">
      {/* 返回按钮 */}
      <div className="detail-header">
        <button className="back-button" onClick={onBack}>
          <svg width="24" height="24" viewBox="0 0 24 24" fill="white">
            <path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.42-1.41L7.83 13H20v-2z" />
          </svg>
        </button>
        <h1 className="detail-title">视频详情</h1>
      </div>

      {/* 视频播放区域 */}
      <div className="video-player-section">
        <div className="video-player">
          {isPlaying ? (
            <video
              controls
              autoPlay
              className="video-element"
              poster={`/api/file/download/img?fileName=${
                video.coverId
              }&token=${getToken()}`}
            >
              <source
                src={`/api/file/download/video?fileName=${video.fileId}${
                  !video.freeState ? `&token=${getToken()}` : ""
                }`}
                type="video/mp4"
              />
              您的浏览器不支持视频播放。
            </video>
          ) : (
            <div className="video-placeholder">
              <img
                src={`/api/file/download/img?fileName=${
                  video.coverId
                }&token=${getToken()}`}
                alt={video.title}
                className="video-poster"
              />
              <button className="play-overlay" onClick={handlePlayVideo}>
                <svg width="60" height="60" viewBox="0 0 24 24" fill="white">
                  <path d="M8 5v14l11-7z" />
                </svg>
              </button>
              {!video.freeState && (
                <div className="vip-badge">
                  <span>VIP</span>
                </div>
              )}
            </div>
          )}
        </div>

        {/* 视频信息 */}
        <div className="video-info-section">
          <h2 className="video-title">{video.title}</h2>
          <div className="video-meta">
            <span className="video-status">
              {video.freeState ? "免费观看" : "VIP专享"}
            </span>
            {video.createdTime && (
              <span className="video-date">
                {new Date(video.createdTime).toLocaleDateString()}
              </span>
            )}
          </div>
          <p className="video-description">{video.title}</p>

          {/* 举报按钮 */}
          <div className="video-actions">
            <button
              className="report-button"
              onClick={() => {
                if (userInfo?.id) setIsReportModalVisible(true);
                else message.error("请先登录");
              }}
              style={{
                background: "none",
                border: "1px solid rgb(71, 126, 255)",
                color: "rgb(71, 126, 255)",
                fontSize: 14,
                padding: "6px 12px",
                borderRadius: 6,
                cursor: "pointer",
                display: "flex",
                alignItems: "center",
                gap: 6,
                marginTop: 12,
                transition: "all 0.3s ease",
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.background = "#ff4757";
                e.currentTarget.style.color = "white";
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.background = "none";
                e.currentTarget.style.color = "#ff4757";
              }}
            >
              <svg
                width="16"
                height="16"
                viewBox="0 0 24 24"
                fill="currentColor"
              >
                <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z" />
              </svg>
              举报视频
            </button>
          </div>
        </div>
      </div>

      {/* 相关视频 */}
      <div className="related-videos-section">
        <h3 className="section-title">相关视频</h3>
        {loading ? (
          <div className="loading">加载中...</div>
        ) : (
          <div className="related-videos-list">
            {relatedVideos.map((relatedVideo) => (
              <div
                key={relatedVideo.id}
                className="related-video-item"
                onClick={() => handleRelatedVideoClick(relatedVideo)}
              >
                <div className="related-video-thumbnail">
                  <img
                    src={`/api/file/download/img?fileName=${
                      relatedVideo.coverId
                    }&token=${getToken()}`}
                    alt={relatedVideo.title}
                  />
                  <div className="related-play-button">
                    <svg
                      width="20"
                      height="20"
                      viewBox="0 0 24 24"
                      fill="white"
                    >
                      <path d="M8 5v14l11-7z" />
                    </svg>
                  </div>
                </div>
                <div className="related-video-info">
                  <h4 className="related-video-title">{relatedVideo.title}</h4>
                  <p className="related-video-description">
                    {relatedVideo.freeState ? "免费观看" : "VIP专享"}
                  </p>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* 举报弹窗 */}
      <Modal
        title="举报视频"
        visible={isReportModalVisible}
        onOk={handleReportSubmit}
        onCancel={handleReportCancel}
        okText="提交举报"
        cancelText="取消"
        centered
        width={500}
      >
        <div style={{ marginBottom: 16 }}>
          <p style={{ color: "#666", marginBottom: 12 }}>
            请详细描述您要举报的问题：
          </p>
          <TextArea
            value={reportContent}
            onChange={(e) => setReportContent(e.target.value)}
            placeholder="请输入举报内容，如：涉及违法违规内容、侵犯版权、虚假信息等..."
            rows={6}
            maxLength={500}
            showCount
            style={{
              resize: "none",
              fontSize: 14,
              lineHeight: 1.6,
            }}
          />
        </div>
        <div style={{ color: "#999", fontSize: 12 }}>
          <p>• 我们会认真处理每一个举报</p>
          <p>• 恶意举报将承担相应责任</p>
        </div>
      </Modal>
    </div>
  );
};

export default VideoDetail;
